package cn.feng.process.demo.core;

import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;

import java.io.Serializable;

/**
 * 统一接口返回值
 *
 * @author zzf
 * @date 2020/6/29 16:32
 */
@Getter
@Setter
@ApiModel("统一接口返回对象")
public class ServiceResponse<T> implements Serializable {

    @ApiModelProperty("数据")
    private T data;

    @ApiModelProperty("状态编号")
    private int code;

    @ApiModelProperty("消息内容")
    private String message;

    @JsonInclude(JsonInclude.Include.NON_NULL)//为null则不序列化
    @ApiModelProperty("报错信息")
    private String error;

    public ServiceResponse(T data, int code, String message) {
        super();
        this.setData(data);
        this.setCode(code);
        this.setMessage(message);
    }

    public ServiceResponse(int code, String message) {
        super();
        this.setCode(code);
        this.setMessage(message);
    }

    public ServiceResponse(RuntimeException e) {
        this.setCode(ResponseCodeEnum.FAIL.getCode());
        this.setMessage(ResponseCodeEnum.FAIL.getDesc());
        //输出栈信息
        StringBuilder buffer = new StringBuilder(e.getMessage()).append("：");
        for (StackTraceElement element : e.getStackTrace()) {
            String className = element.getClassName();
            if (className.contains("com.copm")) {
                buffer.append(className).append("（")
                        .append(element.getMethodName()).append("：")
                        .append(element.getLineNumber()).append("）。").append(System.lineSeparator());
            }
        }
        this.setError(buffer.toString());
    }

    public ServiceResponse(ServiceException e) {
        super();
        this.setCode(e.getCode() == null ? ResponseCodeEnum.FAIL.getCode() : e.getCode());
        this.setMessage(e.getMessage());
    }

    public ServiceResponse(T data, ResponseCodeEnum exceptionEnum) {
        this.message = exceptionEnum.getDesc();
        this.code = exceptionEnum.getCode();
        this.data = data;
    }


    public ServiceResponse(ResponseCodeEnum codeCodeEnum) {
        this.setCode(codeCodeEnum.getCode());
        this.setMessage(codeCodeEnum.getDesc());
    }

    public ServiceResponse() {
    }

    //判断是否成功
    public boolean succeeded() {
        return ResponseCodeEnum.SUCCESS.getCode() == this.code;
    }
}
